<template lang="jade">
    button.el-button(type="button", :class="classObject", @click="click", :disabled="status")
        span.button_text
            slot
</template>
<script>
import { Spinner } from 'spin.js'
export default {
  name: 'loadingBtn',
  props: {
    loading: {
      type: Boolean,
      default: false
    },
    size: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      $dom: '',
      spinner: '',
      start: 0,
      end: 0,
      status: false
    }
  },
  methods: {
    click (e) {
      // 获取当前点击的dom
      let target = e.target
      if (target.tagName === 'SPAN') {
        this.$dom = $(target).parent()
      }
      if (target.tagName === 'BUTTON') {
        this.$dom = $(target)
      }

      this.$emit('click')
    }
  },
  watch: {
    loading: function (value) {
      if (value) {
        this.status = true
        this.start = Date.now()

        let lines = 14
        let radius = this.$dom[0].offsetHeight * 0.15
        let length = radius * 0.6
        let width = radius < 7 ? 2 : 3

        let opts = {
          color: '#fff',
          lines: lines,
          radius: radius,
          length: length,
          width: width,
          zIndex: 'auto',
          top: '50%',
          left: '50%'
        }

        let target = this.$dom[0]
        this.spinner = new Spinner(opts).spin(target)
      } else {
        this.end = Date.now()
        let time = this.end - this.start
        // 默认1秒内不让再点击
        if (time < 1000) {
          setTimeout(() => {
            this.status = false
            !!this.spinner && this.spinner.stop()
          }, 1000 - time)
        } else {
          this.status = false
          !!this.spinner && this.spinner.stop()
        }
      }
    }
  },
  computed: {
    classObject: function () {
      return {
        'loading-btn': this.status,
        'el-button--default': this.status,
        'is-disabled': this.status,

        'el-button--medium': this.size === 'medium',
        'el-button--small': this.size === 'small',
        'el-button--mini': this.size === 'mini',

        'el-button--primary': this.type === 'primary',
        'el-button--success': this.type === 'success',
        'el-button--info': this.type === 'info',
        'el-button--warning': this.type === 'warning',
        'el-button--danger': this.type === 'danger'
      }
    }
  }
}

// {'loading-btn el-button--default is-disabled': status, 'el-button--medium': size === 'medium', 'el-button--small': size === 'small', 'el-button--mini': size === 'mini'}
</script>
<style lang="scss" scoped>
.loading-btn {
  position: relative;

  .button_text {
    visibility: hidden;
  }
}
</style>
